package com.lhkj.iams.wechat.service.impl;

import com.lhkj.iams.wechat.config.mp.WxMpConfiguration;
import com.lhkj.iams.wechat.config.mp.bo.WxMpMessageBo;
import com.lhkj.iams.wechat.service.WxMpAuthService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
  * <p>
  *     描述：公众号授权相关接口
  * </p>
  */
@Service
public class WxMpAuthServiceImpl implements WxMpAuthService {

    private static final Logger log = LoggerFactory.getLogger(WxMpAuthServiceImpl.class);

    @Resource(name = "wxMpService")
    private WxMpService wxMpService;

    @Resource
    private WxMpMessageRouter wxMpMessageRouter;


    @Override
    public String authorize(String redirectUrl, HttpServletResponse response) throws IOException {
        WxMpService targetMpService = wxMpService.switchoverTo(WxMpConfiguration.DEFAULT_APPID);
        // 获取配置的授权域名
        String oauth2redirectUri = targetMpService.getWxMpConfigStorage().getOauth2redirectUri();
        // s:重定向地址 s1：scope s2：state
        String authorizationUrl = targetMpService
                .getOAuth2Service()
                .buildAuthorizationUrl(oauth2redirectUri + redirectUrl,
                WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        log.info("authorizationUrl:{}", authorizationUrl);
        // 前后端分离使用这种方式
//        response.sendRedirect(redirectUrl);
        // 非前后端分离可使用这种方式，记得控制层使用@Controller
        return "redirect:"+authorizationUrl;
    }

    @Override
    public WxOAuth2UserInfo wxOpenIdByCode(String code, String mpId) throws WxErrorException {
        log.debug("获取公众号用户信息：mpId:{}, code:{}", StringUtils.defaultIfBlank(mpId,WxMpConfiguration.DEFAULT_APPID), code);
        System.out.println(wxMpService.switchoverTo(StringUtils.defaultIfBlank(mpId,WxMpConfiguration.DEFAULT_APPID)).getWxMpConfigStorage().toString());
        WxOAuth2AccessToken accessToken = wxMpService.switchoverTo(StringUtils.defaultIfBlank(mpId,WxMpConfiguration.DEFAULT_APPID))
                .getOAuth2Service().getAccessToken(code);
        return wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
    }

    @Override
    public WxJsapiSignature createJsapiSignature(String mpId, String url) throws WxErrorException {
        WxMpService wxMpService1 = wxMpService.switchoverTo(StringUtils.defaultIfBlank(mpId,WxMpConfiguration.DEFAULT_APPID));
        return wxMpService1.createJsapiSignature(url);
    }

    @Override
    public String receiveMessage(WxMpMessageBo wxMpMessageBo) {
        WxMpService wxMpService1 = wxMpService.switchoverTo(StringUtils.defaultIfBlank(wxMpMessageBo.getMpId(),WxMpConfiguration.DEFAULT_APPID));
        String out = null;
        if (wxMpMessageBo.getEncType() == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(wxMpMessageBo.getMessage());
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(wxMpMessageBo.getEncType())) {
            // aes加密的消息
            WxMpConfigStorage wxMpConfigStorage = wxMpService1.getWxMpConfigStorage();
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(wxMpMessageBo.getMessage(), wxMpConfigStorage,
                    wxMpMessageBo.getTimestamp(), wxMpMessageBo.getNonce(), wxMpMessageBo.getMsgSignature());
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toEncryptedXml(wxMpConfigStorage);
        }
        return out;

//        log.debug("\n组装回复信息：{}", out);
//        return out;
//        // 解密消息
//        WxMaMessage wxMaMessage = getWxMaMessage(requestBody, msgSignature, encryptType, signature, timestamp, nonce, "JSON");
//        log.info("收到消息：{}", wxMaMessage);
//        // 转到客服
//        WxMaXmlOutMessage wxMaXmlOutMessage = new WxMaXmlOutMessage();
//        wxMaXmlOutMessage.setToUserName(wxMaMessage.getFromUser());
//        wxMaXmlOutMessage.setFromUserName(wxMaMessage.getToUser());
//        // 转发到客服
//        wxMaXmlOutMessage.setMsgType("transfer_customer_service");
//        wxMaXmlOutMessage.setCreateTime(System.currentTimeMillis());
//        return toWxMaOutMessage(wxMaXmlOutMessage, encryptType);
    }

    /**
     * 解析消息
     *
     * @param requestBody
     * @param msgSignature
     * @param encryptType
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
//    public WxMaMessage getWxMaMessage(String requestBody, String msgSignature, String encryptType, String signature, String timestamp, String nonce, String msgDataFormat) {
//        // 明文传输
//        if (StringUtils.isBlank(encryptType)) {
//            // json
//            if (WxMaConstants.MsgDataFormat.JSON.equals(msgDataFormat)) {
//                return WxMpXmlMessage.fromJson(requestBody);
//            } else {
//                return WxMaMessage.fromXml(requestBody);
//            }
//        }
//        //aes加密
//        else if ("aes".equals(encryptType)) {
//            // json
//            if (WxMaConstants.MsgDataFormat.JSON.equals(msgDataFormat)) {
//                return WxMaMessage.fromEncryptedJson(requestBody, wxMpService.getWxMpConfigStorage());
//            }
//            // xml
//            else {
//                return WxMaMessage.fromEncryptedXml(requestBody, wxMaService.getWxMaConfig(), timestamp, nonce, msgSignature);
//            }
//        }
//        throw new RuntimeException("不可识别的消息加密方式");
//    }
//
//    /**
//     * 返回给微信服务器的消息
//     *
//     * @param wxMaXmlOutMessage
//     * @param encryptType
//     * @return
//     */
//    public String toWxMaOutMessage(WxMaXmlOutMessage wxMaXmlOutMessage, String encryptType) {
//        // 明文传输
//        if (StringUtils.isBlank(encryptType)) {
//            return wxMaXmlOutMessage.toXml();
//        }
////         // aes加密
////        else if ("aes".equals(encryptType)) {
////            return wxMaXmlOutMessage.toEncryptedXml(wxMaService.getWxMaConfig());
////        }
//        throw new RuntimeException("不可识别的消息加密方式");
//    }
}
